package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"os"
	"strings"
)

func main() {
	//conn, err := net.Dial("tcp", "127.0.0.1:2000")
	tcpConn, err := net.DialTCP("tcp", nil, &net.TCPAddr{
		IP:   net.IPv4(127, 0, 0, 1),
		Port: 2000,
	})
	if err != nil {
		log.Fatalln("连接服务器失败:", err)
		return
	}
	defer tcpConn.Close()
	addr := tcpConn.RemoteAddr()
	fmt.Println(addr.Network(), addr.String())
	reader := bufio.NewReader(os.Stdin)
	for {
		readString, err := reader.ReadString('\n')
		if err != nil {
			fmt.Println("从键盘读取数据失败", err)
			continue
		}
		msg := strings.TrimSpace(readString)
		n, err := tcpConn.Write([]byte(msg))
		if err != nil {
			fmt.Println("发送数据失败", err)
			continue
		}
		fmt.Printf("发送的数据为：%s,长度为:%d \n", msg, n)
		b := make([]byte, 1024)
		n, err = tcpConn.Read(b)
		if err != nil {
			fmt.Println("从服务器读取数据失败", err)
			continue
		}
		str := string(b[0:n])
		fmt.Printf("从服务器获取的数据为：%s,长度为:%d \n", str, n)
		if str == "bye" {
			fmt.Printf("bye bye 了 您")
			return
		}
	}
}
